package com.jiutong.meipenggang.ui.activitys;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.AppManager;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.utils.PermissionsResultListener;
import com.jiutong.meipenggang.views.dialog.BaseDialogNormal;
import com.tbruyelle.rxpermissions.Permission;


import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * @author Veken
 */
public class HelpCenterActivity extends BaseActivity {


    @Bind(R.id.rl_common_title_back)
    RelativeLayout rlCommonTitleBack;
    @Bind(R.id.tv_common_title)
    TextView tvCommonTitle;
    @Bind(R.id.ll_common_question)
    LinearLayout llCommonQuestion;
    @Bind(R.id.ll_user_feedback)
    LinearLayout llUserFeedback;
    @Bind(R.id.ll_about_us)
    LinearLayout llAboutUs;
    @Bind(R.id.rl_wechat)
    RelativeLayout rlWechat;
    @Bind(R.id.ll_custom_service)
    LinearLayout llCustomService;
    @Bind(R.id.tv_common_title_options)
    TextView tvCommonTitleOptions;

    /**
     * 客服电话
     */
    private String phone = "187-1847-6218";
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private BaseDialogNormal dialogNormal;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_help_center;
    }

    @Override
    protected void initView() {
        super.initView();
        tvCommonTitle.setText("帮助中心");

    }

    /**
     * ButterKnife的点击事件
     * @param view
     */
    @OnClick({R.id.rl_common_title_back, R.id.ll_common_question, R.id.ll_user_feedback, R.id.ll_about_us, R.id.rl_wechat, R.id.ll_custom_service})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_common_title_back:
                AppManager.getAppManager().finishActivity(this);
                break;
            case R.id.ll_common_question:
                openActivity(CommonQuestionActivity.class);
                break;
            case R.id.ll_user_feedback:
                openActivity(SuggestionBackActivity.class);
                break;
            case R.id.ll_about_us:
                openActivity(AboutUsActivity.class);
                break;
            case R.id.rl_wechat:
                break;
            case R.id.ll_custom_service:
                showCustomServiceDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 拨打电话的dialog
     */
    private void showCustomServiceDialog() {
        if (dialogNormal == null) {
            dialogNormal = new BaseDialogNormal.Builder().
                    layResuorce(R.layout.dialog_custom_service).
                    okViewClickEvent(R.id.tv_dialog_phone_call).
                    cancelViewClickEvent(R.id.tv_dialog_phone_cancel).
                    setContentId(R.id.tv_dialog_phone).
                    setContentText(phone).
                    gravityStyle(Gravity.CENTER).
                    animResource(R.style.dialog_animation_fade).
                    dialogWidth(-2).
                    build();
            dialogNormal.setOnDialogClickListener(new BaseDialogNormal.OnDialogClickListener() {
                @Override
                public void onOkClick() {
//                    checkPermission();
                    //拨打电话之前检查权限
//                    rxPermissions.requestEach(Manifest.permission.CALL_PHONE).subscribe(new Action1<Permission>() {
//                        @Override
//                        public void call(Permission permission) {
//                            if(permission.granted){
//                                CallPhone();
//                            }else if(permission.shouldShowRequestPermissionRationale){
//                                toastShortShow(getResources().getString(R.string.permission_call_phone_hint));
//                            }else{
//                                toastShortShow(getResources().getString(R.string.permission_call_phone_hint));
//                            }
//                        }
//                    });
                    performRequestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1, new PermissionsResultListener() {
                        @Override
                        public void onPermissionGranted() {
                            CallPhone();
                        }

                        @Override
                        public void onPermissionDenied() {
                            toastShortShow(getResources().getString(R.string.permission_call_phone_hint));
                        }
                    });
                }

                @Override
                public void onOk2Click() {

                }
            });
        }
        dialogNormal.show(getSupportFragmentManager(),TAG);
    }

    /**
     * 普通拨打电话的权限申请
     */
    private void checkPermission(){
        // 检查是否获得了权限（Android6.0运行时权限）
        if (ContextCompat.checkSelfPermission(HelpCenterActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(HelpCenterActivity.this,
                    Manifest.permission.CALL_PHONE)) {
                // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                // 弹窗需要解释为何需要该权限，再次请求授权
                Toast.makeText(HelpCenterActivity.this, "请授权！", Toast.LENGTH_LONG).show();

                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(HelpCenterActivity.this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
            }
        } else {
            // 已经获得授权，可以打电话
            CallPhone();
        }
    }

    /**
     * 拨打电话的Intent
     */
    private void CallPhone() {
        // 拨号：激活系统的拨号组件 意图对象：动作 + 数据
        Intent intent = new Intent();
        // 设置动作
        intent.setAction(Intent.ACTION_CALL);
        // 设置数据
        Uri data = Uri.parse("tel:" + phone.replaceAll("-",""));
        intent.setData(data);
        startActivity(intent);
    }

    /**
     * 处理权限申请的回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    CallPhone();
                } else {
                    // 授权失败！
                    Toast.makeText(this, "授权失败！", Toast.LENGTH_LONG).show();
                }
                break;
            }
            default:
                break;
        }

    }
}
